import React, { useEffect } from 'react';
import { Button, Drawer, Form, Input, message, Modal, Select, Space, Spin } from 'antd';
import Keywords from 'common/component/Keywords';
import FileUpload from "@/components/FileUpload";
import { articleNormalCategory, FileGroup, UserType } from "common/utils/data";
import { useRequest } from "ahooks";
import { articleV1ControllerUpdateMine, articleV1ControllerCreateMine, articleV1ControllerShowMine } from "@/services/auto/article";
import { useModel } from "@umijs/max";

// 表单布局
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const tailLayout = {
  wrapperCol: { offset: 6, span: 18 },
};

export default function RightDraw(props) {
  const {data: user} = useModel('user')

  const {
    drawerVisible,
    setDrawerVisible,
    activeArticleUuid,
    setActiveArticleUuid,
    refreshEditor,
    refreshList,
    beforeSave,
  } = props;

  const [form] = Form.useForm<FormValues>();

  const {data: getArticlesDetailData,runAsync: getArticlesDetailRun,loading: getArticlesDetailLoading} = useRequest(articleV1ControllerShowMine, {
    manual: true,
    onSuccess: res=>{
      form.setFieldsValue({
        title: res.title,
        desc: res.desc,
        keywords: res.keywords,
        categories: res.categories,
        thumbnails: res.thumbnails
      })
    }
  })

  const {run: postArticlesRun,loading: postArticlesLoading} = useRequest(articleV1ControllerCreateMine, {
    manual: true,
    onSuccess: (res)=>{
      message.success({
        content: '新增成功，请编辑内容'
      })
      refreshEditor.current?.();
      refreshList.current?.();
      setDrawerVisible(false);
      setActiveArticleUuid(res.uuid);
    }
  })

  const {run: patchArticlesRun,loading: patchArticlesLoading} = useRequest(articleV1ControllerUpdateMine, {
    manual: true,
    onSuccess: ()=>{
      message.success({
        content: '编辑成功，若文章之前已上架需要重新提交审核'
      })
      refreshEditor.current?.();
      refreshList.current?.();
      setDrawerVisible(false);
    }
  })

  useEffect(()=>{
    if(drawerVisible){
      if(activeArticleUuid){
        getArticlesDetailRun({uuid: activeArticleUuid});
      }
    }else {
      form.resetFields();
    }
  },[drawerVisible])

  return (
    <Modal
      title="文章属性"
      closable={false}
      onCancel={() => {
        setDrawerVisible(false);
      }}
      open={drawerVisible}
      width={500}
      onOk={()=>{
        return form.validateFields().then(values=>{
          const param: API.ArticleCreateDto = {
            title: values.title,
            desc: values.desc,
            keywords: values.keywords,
            categories: values.categories,
            thumbnails: values.thumbnails,
          };
          if(activeArticleUuid){
            return beforeSave(getArticlesDetailData?.status).then(()=>{
              patchArticlesRun({uuid: activeArticleUuid}, param);
            })
          }else {
            return postArticlesRun(param);
          }
        })
      }}
    >
      <Spin spinning={getArticlesDetailLoading}>
        <Form
          {...layout}
          form={form}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[
              { required: true, message: '请输入标题' },
            ]}
          >
            <Input maxLength={50} />
          </Form.Item>
          <Form.Item name="desc" label="引言">
            <Input.TextArea showCount maxLength={1000} />
          </Form.Item>
          {user?.userType === UserType.ADMIN && <Form.Item
            name="categories"
            label="Tag"
            rules={[
              { required: true, type: 'array', message: '请选择Tag' },
            ]}
          >
            <Select
              showSearch
              mode="multiple"
              optionFilterProp="label"
              options={articleNormalCategory.$listSelect}/>
          </Form.Item>}
          <Form.Item
            name="thumbnails"
            label="封面图"
          >
            <FileUpload fileGroup={FileGroup.ARTICLE} max={3} />
          </Form.Item>
          <Form.Item name="keywords" label="关键词">
            <Keywords />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};

interface FormValues extends API.ArticleCreateDto{
}
